/**
 * 安全评估证明材料收集系统 API（对齐后端 /proofmapper 接口）
 */

import { typedHttp } from '@/utils/typedHttp';
import type { 
  SharedResponse, 
  SnapshotResponse, 
  SnapshotListResponse,
  SnapshotCreate,
  SnapshotUpdate
} from '@/types/ProofMapper';

class ProofMapperAPI {
  private baseUrl = '/proofmapper';

  // 上传并解析 PDF，创建会话
  async parsePdf(file: File): Promise<{ shared_id: string } & SharedResponse> {
    const formData = new FormData();
    formData.append('file', file);
    return typedHttp.post<{ shared_id: string } & SharedResponse>(`${this.baseUrl}/parse`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 0,
    });
  }

  // 获取会话当前 shared（精简版）
  async getSession(sharedId: string): Promise<SharedResponse> {
    return typedHttp.get<SharedResponse>(`${this.baseUrl}/sessions/${sharedId}`);
  }

  // 获取会话修改历史与摘要
  async getHistory(sharedId: string): Promise<{ modification_log: any[]; summary: any }> {
    return typedHttp.get<{ modification_log: any[]; summary: any }>(`${this.baseUrl}/sessions/${sharedId}/history`);
  }

  // 应用自然语言指令
  async applyUserInput(sharedId: string, userInput: string): Promise<SharedResponse> {
    return typedHttp.post<SharedResponse>(`${this.baseUrl}/sessions/${sharedId}/apply`,
      { user_input: userInput },
      { timeout: 0 });
  }

  // 回滚最近一次修改
  async rollback(sharedId: string): Promise<SharedResponse> {
    return typedHttp.post<SharedResponse>(`${this.baseUrl}/sessions/${sharedId}/rollback`);
  }

  // 删除会话
  async deleteSession(sharedId: string): Promise<{ ok: boolean }> {
    return typedHttp.delete<{ ok: boolean }>(`${this.baseUrl}/sessions/${sharedId}`);
  }

  // ===== 快照管理（多版本支持）=====

  // 获取指定类型的快照列表
  async getSnapshots(assessmentType: string): Promise<SnapshotListResponse> {
    return typedHttp.get<SnapshotListResponse>(
      `${this.baseUrl}/snapshots/${encodeURIComponent(assessmentType)}`
    );
  }

  // 获取单个快照并初始化会话
  async getSnapshotById(assessmentType: string, snapshotId: string): Promise<SnapshotResponse> {
    return typedHttp.get<SnapshotResponse>(
      `${this.baseUrl}/snapshots/${encodeURIComponent(assessmentType)}/${snapshotId}`
    );
  }

  // 创建新快照
  async createSnapshot(payload: SnapshotCreate): Promise<SnapshotResponse> {
    return typedHttp.post<SnapshotResponse>(`${this.baseUrl}/snapshots`, payload);
  }

  // 更新快照
  async updateSnapshot(snapshotId: string, payload: SnapshotUpdate): Promise<SnapshotResponse> {
    return typedHttp.put<SnapshotResponse>(
      `${this.baseUrl}/snapshots/${snapshotId}`,
      payload
    );
  }

  // 删除快照
  async deleteSnapshot(snapshotId: string): Promise<{ ok: boolean; id: string }> {
    return typedHttp.delete<{ ok: boolean; id: string }>(
      `${this.baseUrl}/snapshots/${snapshotId}`
    );
  }
}

export const proofMapperAPI = new ProofMapperAPI();
